import AddAccount from '@/pages/admin/account/components/AddAccount';
import EditAccount from '@/pages/admin/account/components/EditAccount';
import {
  deleteAccount,
  pageAccount,
  resetAccountBindWeChat,
} from '@/services/api/api-admin-account';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { message, Space, Tag } from 'antd';
import React, { Key, useEffect, useRef, useState } from 'react';

interface TabAccountProps {
  organizationId?: string | undefined;
  onSaveSuccess: () => void;
}
const TabAccount: React.FC<TabAccountProps> = ({ organizationId, onSaveSuccess }) => {
  const [selectedAccountRowKeys, setSelectedAccountRowKeysState] = useState<React.Key[]>([]);

  const userRef = useRef<ActionType>();

  const columns: ProColumns<AdminAccountData.Account>[] = [
    {
      title: '组织',
      key: 'organizationName',
      dataIndex: 'organizationName',
      width: '180px',
      hideInTable: true,
    },
    {
      title: '账号',
      key: 'name',
      dataIndex: 'name',
      width: '80px',
      fixed: 'left',
    },
    {
      title: '激活',
      key: 'isActivation',
      dataIndex: 'isActivation',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用', status: 'Error' },
        1: { text: '启用', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '绑定微信',
      key: 'isWechatUnionid',
      dataIndex: 'isWechatUnionid',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '60px',
    },
    {
      title: '关注公众号',
      key: 'isWechatWxmpSubscribe',
      dataIndex: 'isWechatWxmpSubscribe',
      valueType: 'select',
      valueEnum: {
        0: { text: '否', status: 'Error' },
        1: { text: '是', status: 'Success' },
      },
      width: '70px',
    },
    {
      title: '电话',
      key: 'phone',
      dataIndex: 'phone',
      width: '120px',
      order:1
    },
    {
      title: '组织',
      key: 'organizationName',
      dataIndex: 'organizationName',
      width: '180px',
      hideInSearch: true,
      render: (_, row) => (
        <Space size={[0, 'small']} wrap>
          {row.organizationNames.map((item) => (
            <Tag key={row.id + row.phone + item}>{item}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '最后登录时间',
      key: 'loginTime',
      dataIndex: 'loginTime',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '操作',
      valueType: 'option',
      width: '120px',
      fixed: 'right',
      render: (_, row, index, action) => [
        <EditAccount
          key="edit_role"
          account={row}
          onRefurbish={() => {
            userRef.current?.reload();
          }}
        />,
        <a
          key="a_reset_bind_wechat"
          onClick={async () => {
            const response = await resetAccountBindWeChat({ id: row.id });
            if (response.code === 0) {
              message.success('重置成功');
              userRef.current?.reload();
            }
          }}
        >
          重置微信
        </a>,
      ],
    },
  ];

  useEffect(() => {
    userRef.current?.reloadAndRest();
  }, [organizationId]);

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageAccount({
      organizationId,
      ...params,
    });

    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  return (
    <ProTable<AdminAccountData.Account>
      // ghost
      // search={false}
      columns={columns}
      actionRef={userRef}
      request={request}
      rowSelection={{
        type: 'checkbox',
        onChange: (selectedRowKeys: Key[], selectedRows: any) => {
          setSelectedAccountRowKeysState(selectedRowKeys);
        },
      }}
      sticky
      rowKey="id"
      tableLayout="fixed"
      dateFormatter="string"
      bordered
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      scroll={{
        x: '1300px',
      }}
      toolBarRender={() => [
        <AddAccount
          key="add_account"
          onRefurbish={() => {
            userRef.current?.reload();
            onSaveSuccess();
          }}
        />,
      ]}
      tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) =>
        selectedAccountRowKeys.length > 0 && (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
          </Space>
        )
      }
      tableAlertOptionRender={() => {
        return (
          <Space size={16}>
            <a
              onClick={async () => {
                try {
                  const response = await deleteAccount({ ids: selectedAccountRowKeys });
                  if (response.code === 0) {
                    message.success('批量删除成功');
                    setSelectedAccountRowKeysState([]);
                    userRef.current?.reload();
                    userRef?.current?.clearSelected();
                  }
                } catch (error) {
                  message.error('批量删除失败');
                }
                userRef.current?.reload();
              }}
            >
              删除
            </a>
          </Space>
        );
      }}
    />
  );
};
export default TabAccount;
